package com.example.gatewayservice.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.RedisTemplate;
//import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.lang.annotation.Annotation;
import java.util.Arrays;
import java.util.List;

/**
 * @author likaiping
 * @createTime 2024/7/3 12:30
 */
@Component
public class AuthFilter implements GlobalFilter, Order {
    @Resource
    private RedisTemplate redisTemplate;
    private static final List<String> WHITE_LIST = Arrays.asList("/admin/login", "/admin/register",
            "/goods/getAll", "/goods/getOne","/goods/detail","/admin/tologin","/admin/toregister",
            "/websocketSeckill" ,"/topic/seckill","/test/testnacos","/subscribe","/notifyToUser");
    @Override
    public Class<? extends Annotation> annotationType() {
        return null;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        String path = request.getURI().getPath();
        System.out.println(path);
        if (WHITE_LIST.contains(path)) {
            //白名单路径直接放行
            return chain.filter(exchange);
        }

        //token 123456
        HttpHeaders headers = request.getHeaders();
        System.out.println(headers);
        List<String> tokens = headers.get("Authorization");
        System.out.println("AuthFilter中tokens:"+tokens);
        System.out.println(tokens);
        if (tokens == null || redisTemplate.opsForValue().get(tokens.get(0))==null) {
            System.out.println("设置401状态码 token is null");
            // 未登录 401状态码
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //放行 进入下一个过滤器
        System.out.println("通过AuthFilter过滤器，放行");
        return chain.filter(exchange);
    }

    @Override
    public int value() {
        return 0;
    }
}
